#
#  @Author: january.cjy 
#  @Date: 2021-09-24 17:34:17 
#  @Last Modified by:   january.cjy 
#  @Last Modified time: 2021-09-24 17:34:17 
#
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

import os
import re
import subprocess
import string
import sys

LLVM_CONFIG="llvm-config"

LLVM_LIBS=[]
LLVM_SYSTEM_LIBS=[]
LLVM_CXXFLAGS=[]
LLVM_LDFLAGS=[]

def fetch_libs():
    proc = subprocess.Popen(args=[LLVM_CONFIG,"--libs"],stdout=subprocess.PIPE)
    proc.wait()
    content = str(proc.stdout.read(),'utf-8').strip()
    tmp = content.split()
    for lib in tmp:
        LLVM_LIBS.append(lib[2:])

def fetch_ldflags():
    proc1 = subprocess.Popen(args=[LLVM_CONFIG,"--ldflags","--system-libs"],stdout=subprocess.PIPE)
    proc1.wait()
    line = proc1.stdout.readline()
    while line:
        i = str(line,'utf-8').strip()
        LLVM_LDFLAGS.append(i)
        line = proc1.stdout.readline()

def fetch_cxxflags():
    proc = subprocess.Popen(args=[LLVM_CONFIG,"--cxxflags"],stdout=subprocess.PIPE)
    proc.wait()
    content = str(proc.stdout.read(),'utf-8').strip()
    tmp = content.split()
    for f in tmp:
        LLVM_CXXFLAGS.append(f)

fetch_libs()
fetch_ldflags()
fetch_cxxflags()

script_path: str
# if(os.path.basename(os.path.abspath(os.path.curdir))=='oa++'):
#     cwd=os.path.abspath(os.path.curdir)
# elif(os.path.basename(os.path.abspath('..'))):
#     cwd=os.path.abspath('..')

script_path=os.path.abspath(__file__)
while True:
    if(os.path.basename(script_path)=='oa++' or os.path.basename(script_path)=='oa' or script_path=='/'):
         break;
    script_path=os.path.dirname(script_path)

# print(script_path)

if(script_path=='/'):
    print('cmake_configure.py is not in oa++ project directory.',file=sys.stderr)
    exit(1)

# print(cwd)
LLVM_CMAKE_FILE = open(file=script_path+'/LLVM.cmake',mode='w+')
# LLVM_CMAKE_FILE.write()
configure: str
LLVM_CMAKE_FILE.write('set(LLVM_LIBS\n')
for lib in LLVM_LIBS:
    LLVM_CMAKE_FILE.write('\t'+lib+'\n')
LLVM_CMAKE_FILE.write(')\n')
LLVM_CMAKE_FILE.write('\n')
LLVM_CMAKE_FILE.write('set(LLVM_LDFLAGS\n')
for flag in LLVM_LDFLAGS:
    LLVM_CMAKE_FILE.write('\t'+flag+'\n')
LLVM_CMAKE_FILE.write(')\n')
LLVM_CMAKE_FILE.write('\n')
LLVM_CMAKE_FILE.write('set(LLVM_CXXFLAGS\n')
for flag in LLVM_CXXFLAGS:
    LLVM_CMAKE_FILE.write('\t'+flag+'\n')
LLVM_CMAKE_FILE.write(')\n')